<!-- 用户列表 -->
<template>
  <div class="users">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="">用户管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 布局 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 搜索 -->
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUsesDataFile"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsesDataFile"
              >搜索</el-button
            >
          </el-input>
        </el-col>
        <!-- 添加 -->
        <el-col :span="4"
          ><el-button type="primary" @click="isAddUser = true"
            >添加用户</el-button
          ></el-col
        >
      </el-row>
      <!-- 用户列表 -->
      <el-table :data="usersData" stripe border>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="手机"> </el-table-column>+
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <!-- 修改用户状态 -->
          <template slot-scope="scope">
            <!--作用域插槽 -->
            <!-- {{ scope.row }}可以取到当前列表项数据 -->
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#409EFF"
              inactive-color="#DCDFE6"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!--作用域插槽 -->
            <!-- {{ scope.row }} -->
            <!-- {{ scope.row }}可以取到当前列表项数据 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editUserInformation(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <el-tooltip content="分配角色" placement="top" :enterable="false">
              <el-button
                type="info"
                icon="el-icon-setting"
                size="mini"
                @click="allocationRoles(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户弹出层 -->
    <el-dialog
      title="添加用户"
      :visible.sync="isAddUser"
      width="50%"
      @close="addUserDataClose"
    >
      <span class="dialog_input_box">
        <el-form
          ref="userInfoRef"
          :model="userInfo"
          :rules="userInfoRules"
          label-width="80px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userInfo.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="userInfo.password"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="userInfo.mobile"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userInfo.email"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isAddUser = false">取 消</el-button>
        <el-button type="primary" @click="submitAddUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户弹出层 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="isEditUser"
      width="50%"
      @close="editUserDataClose"
    >
      <span class="dialog_input_box">
        <el-form
          ref="editUserInfoRef"
          :model="editUserInfo"
          :rules="editUserInfoRules"
          label-width="80px"
        >
          <el-form-item label="用户名">
            <el-input
              v-model="editUserInfo.username"
              :disabled="true"
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="editUserInfo.mobile"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editUserInfo.email"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isEditUser = false">取 消</el-button>
        <el-button type="primary" @click="submitEditUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog
      title="分配角色"
      :visible.sync="isAllocationRoles"
      width="50%"
      @close="allocationRolesClose"
    >
      <p class="select_text">
        用户名:<span>{{ userRolesList.username }}</span>
      </p>
      <p class="select_text">
        当前角色:<span>{{ userRolesList.role_name }}</span>
      </p>
      <p class="select_text">
        选择新角色：<el-select v-model="selectRolesId" placeholder="请选择">
          <el-option
            v-for="item in allRolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isAllocationRoles = false">取 消</el-button>
        <el-button type="primary" @click="submitAllocationRoles"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import {
  getUsersData,
  changetUserState,
  addUserInformation,
  queryUserInformation,
  submitEditUserInformation,
  removeUserInformation,
  getAllRoles,
  putAllocationRoles,
} from "../../service/users";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      // 分页数据
      queryInfo: {
        query: "",
        pagenum: 1, //当前的页码
        pagesize: 10, //每页显示多少条数据
      },
      usersData: [], // 用户列表数据
      total: 0, //一共多少数据
      isAddUser: false, //添加用户弹出层
      isEditUser: false, //修改用户弹出层
      isAllocationRoles: false, //分配角色
      allRolesList: [], //所有角色列表
      selectRolesId: "", //选中的角色ID
      userInfo: {
        username: "",
        password: "",
        mobile: "",
        email: "",
      }, //添加用户的表单数据
      // 分配角色的用户列表信息
      userRolesList: {},
      editUserInfo: {
        mobile: "",
        email: "",
      },
      userInfoRules: {
        //添加用户的表单验证
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 4, max: 8, message: "长度在 4 到 8 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 4, max: 8, message: "长度在 4 到 8 个字符", trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            validator: function (rule, value, callback) {
              if (/^1[34578]\d{9}$/.test(value) == false) {
                callback(new Error("请输入正确的手机号"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            validator: function (rule, value, callback) {
              if (/\w+@[a-z0-9]+\.[a-z]{2,4}/.test(value) == false) {
                callback(new Error("请输入正确的邮箱号"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
      editUserInfoRules: {
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            validator: function (rule, value, callback) {
              if (/^1[34578]\d{9}$/.test(value) == false) {
                callback(new Error("请输入正确的手机号"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            validator: function (rule, value, callback) {
              if (/\w+@[a-z0-9]+\.[a-z]{2,4}/.test(value) == false) {
                callback(new Error("请输入正确的邮箱号"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
      // 分配角色验证
      allocationRolesRules: {
        // username: [
        //   { required: true, message: "请输入用户名", trigger: "blur" },
        //   { min: 4, max: 8, message: "长度在 4 到 8 个字符", trigger: "blur" },
        // ],
        // role_name: [
        //   { required: true, message: "请输入密码", trigger: "blur" },
        //   { min: 4, max: 8, message: "长度在 4 到 8 个字符", trigger: "blur" },
        // ],
      },
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    //获取用户信息
    getUsesDataFile() {
      getUsersData(this.queryInfo).then((res) => {
        console.log(res);
        this.usersData = res.data.users;
        this.total = res.data.total;
      });
    },
    //监听每页多少条数据变化
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUsesDataFile();
    },
    //监听当前页的变化
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUsesDataFile();
    },
    // 改变用户状态
    userStateChange(userStateRow) {
      changetUserState(
        `users/${userStateRow.id}/state/${userStateRow.mg_state}`
      ).then((res) => {
        if (res.meta.status != 200) {
          userStateRow.mg_state = !userStateRow.mg_state;
          return this.$message.error("更新用户状态失败！");
        } else {
          this.$message.success("更新用户状态成功！");
        }
      });
    },
    // 提交新增用户
    submitAddUser() {
      this.$refs.userInfoRef.validate((valid) => {
        if (valid) {
          addUserInformation(this.userInfo).then((res) => {
            if (res.meta.status == 201) {
              this.isAddUser = false;
              this.getUsesDataFile();
              this.$message.success("添加成功！");
            } else {
              this.isAddUser = false;
              this.$message.error("添加失败！");
            }
          });
        } else {
          return;
        }
      });
    },
    // 根据ID查询用户信息
    editUserInformation(id) {
      this.isEditUser = true;
      queryUserInformation(`users/${id}`).then((res) => {
        this.editUserInfo = res.data;
      });
    },

    submitEditUser() {
      this.$refs.editUserInfoRef.validate((valid) => {
        if (valid) {
          submitEditUserInformation(`users/${this.editUserInfo.id}`, {
            mobile: this.editUserInfo.mobile,
            email: this.editUserInfo.email,
          }).then((res) => {
            if (res.meta.status == 200) {
              this.isEditUser = false;
              this.getUsesDataFile();
              this.$message.success("修改成功！");
            } else {
              this.isEditUser = false;
              this.$message.error("修改失败！");
            }
          });
        }
      });
    },

    //根据ID删除用户信息
    removeUserById(id) {
      console.log(id);
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          removeUserInformation(`users/${id}`).then((res) => {
            this.getUsesDataFile();
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 分配角色事件
    allocationRoles(userRolesList) {
      this.userRolesList = userRolesList;
      this.isAllocationRoles = true;
      getAllRoles().then((res) => {
        if (res.meta.status == 200) {
          this.allRolesList = res.data;
        } else {
          this.$message.error("获取角色列表失败！");
        }
      });
    },
    // 提交分配角色
    submitAllocationRoles() {
      if (!this.selectRolesId)
        return this.$message.error("请选择要分配的角色!");
      putAllocationRoles(`users/${this.userRolesList.id}/role`, {
        rid: this.selectRolesId,
      }).then((res) => {
        if (res.meta.status == 200) {
          this.$message.success("分配角色成功！");
          this.getUsesDataFile();
          this.isAllocationRoles = false;
        } else {
          this.$message.error("分配角色失败！");
        }
      });
    },
    //关闭添加弹框清除数据
    addUserDataClose() {
      this.$refs.userInfoRef.resetFields();
    },
    //关闭修改弹框清除数据
    editUserDataClose() {
      this.$refs.editUserInfoRef.resetFields();
    },
    // 关闭分配角色弹框
    allocationRolesClose() {
      this.allRolesList = {};
      this.selectRolesId = "";
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getUsesDataFile();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类
.users {
  .el-breadcrumb {
    font-size: 16px;
    margin-bottom: 20px;
  }
  .el-card {
    width: 100%;
    .el-table {
      width: 100%;
      margin-top: 20px;
      margin-bottom: 20px;
    }
  }
  .select_text {
    margin: 20px 0;
    font-size: 16px;
    span {
      color: rgb(228, 178, 87);
      padding-left: 10px;
      font-weight: bold;
    }
  }
}
</style>